import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/app_nav.dart';
import 'package:gim_plugin_example/components/ios_options.dart';
import 'package:gim_plugin_example/global.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/liver_1v1_room_overlay.dart';
import 'package:gim_plugin_example/sdk/gim_sdk.dart';
import 'package:gim_plugin_example/utils/image_utils.dart';
import 'package:gim_plugin_example/utils/permission_utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../../icons.dart';
import '../pg_chat_room_store.dart';

class BottomLayout extends StatelessWidget {
  Future<void> sendImageMsg(BuildContext context, {required bool isPhoto}) async {
    PgChatRoomStore store = context.read<PgChatRoomStore>();
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig:
          AssetPickerConfig(requestType: isPhoto ? RequestType.image : RequestType.video, maxAssets: isPhoto ? 9 : 1),
    );
    if (result == null || result.isEmpty) {
      return;
    }
    for (var value in result) {
      var file = await value.file;
      if (isPhoto) {
        var res = await gimSdk.gim.sendImageMsg(
            toUid: store.remoteUid,
            msg: ImageMsg(url: file!.path, width: value.width, height: value.height),
            pushTitle: store.remoteNickname,
            pushContent: '发来一张图片',
            placeholder: (msg) {
              store.addMsg(msg);
            });
        store.updateMsgByPreId(res!);
      } else {
        var tempDir = await getTemporaryDirectory();
        var coverFile = await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg').create();
        coverFile.writeAsBytesSync((await value.thumbnailData)!);
        var coverInfo = await ImageUtils.getImageWidthAndHeight(coverFile.path);
        var res = await gimSdk.gim.sendVideoMsg(
            toUid: store.remoteUid,
            msg: VideoMsg(
                url: (await value.originFile)!.path,
                cover: coverFile.path,
                width: coverInfo.width,
                height: coverInfo.height,
                dur: value.videoDuration.inSeconds),
            pushTitle: store.remoteNickname,
            pushContent: '发来一个视频',
            placeholder: (msg) {
              store.addMsg(msg);
            });
        Future.delayed(const Duration(milliseconds: 100)).then((_) => coverFile.delete());
        store.updateMsgByPreId(res!);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(left: 30, right: 30, bottom: 0),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            CupertinoButton(
                onPressed: () async {
                  sendImageMsg(context, isPhoto: true);
                },
                child: iconImChoosePhoto(34)),
            CupertinoButton(
                onPressed: () async {
                  sendImageMsg(context, isPhoto: false);
                },
                child: iconImChooseVideo(34)),
            CupertinoButton(
                onPressed: () async {
                  if (!(await applyCameraPermission(context: context))) {
                    return;
                  }
                  if (!(await applyMicrophonePermission(context: context))) {
                    return;
                  }
                  PgChatRoomStore store = context.read<PgChatRoomStore>();
                  Global global = context.read<Global>();
                  String channelName = global.uid!;
                  IosOptions.showBottomOptions(context, items: [
                    IosOptionItem(
                        label: "视频通话",
                        onTap: () async {
                          var sid = await gimSdk.gim.signalingInvite(
                              uid: store.remoteUid,
                              extData: json.encode({
                                'uid': global.uid,
                                'channelName': channelName,
                                'videoCall': true,
                                'nickname': global.nickname,
                                'avatar': global.avatar,
                                'gender': global.gender ?? 0,
                              }),
                              pushTitle: global.nickname!,
                              pushContent: '邀请你视频通话');
                          if (sid == null) return;
                          //启动holding页面
                          liver1v1roomOverlay.open(context,
                              videoCall: true,
                              channelName: channelName,
                              master: true,
                              signalingId: sid,
                              remoteUid: store.remoteUid,
                              remoteNickname: store.remoteNickname,
                              remoteAvatar: store.remoteAvatar);
                        }),
                    IosOptionItem(
                        label: "语音通话",
                        onTap: () async {
                          var sid = await gimSdk.gim.signalingInvite(
                              uid: store.remoteUid,
                              extData: json.encode({
                                'uid': global.uid,
                                'channelName': channelName,
                                'videoCall': false,
                                'nickname': global.nickname,
                                'avatar': global.avatar,
                                'gender': global.gender ?? 0,
                              }),
                              pushTitle: global.nickname!,
                              pushContent: '邀请你视频通话');
                          if (sid == null) return;
                          //启动holding页面
                          liver1v1roomOverlay.open(context,
                              videoCall: false,
                              channelName: channelName,
                              master: true,
                              signalingId: sid,
                              remoteUid: store.remoteUid,
                              remoteNickname: store.remoteNickname,
                              remoteAvatar: store.remoteAvatar);
                        }),
                  ]);
                },
                child: iconImRtc(34)),
          ],
        ));
  }
}
